package track

import (
	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/app"
	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/database"
	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/paginator"

	"github.com/gofiber/fiber/v2"
)

func Get(id uint64) (track Track) {
	database.DB.Where("id", id).First(&track)
	return
}

func GetBy(field, value string) (track Track) {
	database.DB.Where("? = ?", field, value).First(&track)
	return
}

func All() (tracks []Track) {
	database.DB.Order("id desc").Find(&tracks)
	return
}

func IsExist(field, value string) bool {
	var count int64
	database.DB.Model(Track{}).Where("? = ?", field, value).Count(&count)
	return count > 0
}

func IsExistTrack(fromId uint64, toId uint64) bool {
	var count int64
	database.DB.Model(Track{}).Where(database.DB.Model(Track{}).Where("from_id = ? and to_id = ?", fromId, toId)).Or(database.DB.Model(Track{}).Where("from_id = ? and to_id = ?", toId, fromId)).Count(&count)
	return count > 0
}

// Paginate 分页内容
func Paginate(c *fiber.Ctx, perPage int) (tracks []Track, paging paginator.Paging) {
	paging = paginator.Paginate(
		c,
		database.DB.Model(Track{}),
		&tracks,
		app.V1URL(database.TableName(&Track{})),
		perPage,
	)
	return
}

func GetTracksWithName() (tracks []Track) {
	database.DB.Preload("From").Preload("To").Order("id desc").Find(&tracks)
	return
}
